import java.awt.Color;
import java.util.*;

public class MainGrid 
{
	private SubGrid[][] mainGrid;

	
	public MainGrid()
	{
		mainGrid = new SubGrid[3][3]; 
		initMainGrid();
	}
	
	public void initMainGrid()
	{
		for( int i = 0; i < mainGrid.length; i++)
		{
			for( int j = 0; j < mainGrid[i].length; j++ )
			{
				mainGrid[i][j] = new SubGrid(i,j);
			}
		}
	}
	
	public SubGrid get(int row, int col)
	{
		return mainGrid[row][col]; 
	}
	
	public void checkWinner()
	{
		boolean winner = false; 
		Color color; 
		
		//first check if won rows
		for( int i = 0; i < mainGrid.length; i++ )
		{
			winner = true; 
			
			if( mainGrid[i][0].hasWinner() )
			{
				color = mainGrid[i][0].getWinnerColor(); 
				
				for( int j = 1; j < mainGrid[i].length; j++)
				{
					if( mainGrid[i][j].hasWinner() )
					{
						if(!color.equals(mainGrid[i][j].getWinnerColor()))
						{
							winner = false; 
							break; 
						}
					}
				}
				
				if( winner )
				{
					winner = true; 
					//celebrate(color);
				}
			}
			else
			{
				winner = false; 
			}
		}
		
		
		for( int j = 0; j < mainGrid[0].length; j++ )
		{
			winner = true; 
			
			if( mainGrid[0][j].hasWinner() )
			{
				color = mainGrid[0][j].getWinnerColor(); 
				
				for( int i = 1; i < mainGrid.length; i++)
				{
					if( mainGrid[i][j].hasWinner() )
					{
						if(!color.equals(mainGrid[i][j].getWinnerColor()))
						{
							winner = false; 
							break; 
						}
					}
				}
				
				if( winner )
				{
					winner = true; 
					//celebrate(color);
				}
			}
			else
			{
				winner = false; 
			}
		}
		
		if( mainGrid[0][0].hasWinner() )
		{
			color = mainGrid[0][0].getWinnerColor(); 
			winner = true; 
			int row = 1; 
			int col = 1; 
			
			while( row < mainGrid.length && col < mainGrid[row].length && mainGrid[row][col].hasWinner() )
			{
				if( color.equals(mainGrid[row][col].getWinnerColor()))
				{
					row++;
					col++;
					winner = true; 
				}
				else
				{
					winner = false; 
					break; 
				}
			}
			
			if( winner )
			{
				winner = true; 
				//celebrate(color); 
			}
		}
		
		if( mainGrid[mainGrid.length][0].hasWinner() )
		{
			color = mainGrid[mainGrid.length][0].getWinnerColor(); 
			winner = true; 
			int row = mainGrid.length - 1; 
			int col = 1; 
			
			while( row < mainGrid.length && col < mainGrid[row].length && mainGrid[row][col].hasWinner() )
			{
				if( color.equals(mainGrid[row][col].getWinnerColor()))
				{
					row--;
					col++;
					winner = true; 
				}
				else
				{
					winner = false; 
					break; 
				}
			}
			
			if( winner )
			{
				winner = true; 
				//celebrate(color); 
			}
		}
		
	}
	
	
	public void celebrate(Color c)
	{
		for( int i = 0; i < mainGrid.length; i++ )
		{
			for( int j = 0; j < mainGrid[i].length; j++ )
			{
				mainGrid[i][j].colorBoard(c);
			}
		}
	}
	
	
	
	
}
